import 'dart:async';

import 'package:flutter/material.dart';
import 'package:app/utils/utils.dart';

class TimeCounter extends StatefulWidget {
  final int targetTimestamp;
  final double spacing;
  final isMin;
  final Color color;
  const TimeCounter({
    super.key,
    required this.targetTimestamp,
    this.spacing = 10.0,
    this.isMin = false,
    this.color = Colors.black,
  });

  static const TextStyle _textStyleBase = TextStyle(
    fontWeight: FontWeight.bold,
    fontFamily: "led",
    fontFamilyFallback: ["Roboto"],
  );

  @override
  State<TimeCounter> createState() => _TimeCounterState();
}

class _TimeCounterState extends State<TimeCounter>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  TimeDifference _timeDiff = TimeDifference(
    days: '0',
    hours: '00',
    minutes: '00',
    seconds: '00',
  );

  TextStyle get _textStyle =>
      TimeCounter._textStyleBase.copyWith(fontSize: widget.isMin ? 20 : 40);
  Timer? _timer;
  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..repeat(reverse: true);
    _startTimer();
  }

  void _startTimer() {
    _updateTime();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _updateTime();
    });
  }

  void _updateTime() {
    if (!mounted) return;
    setState(() {
      _timeDiff = Utils.calculateTimeDifference2(
        widget.targetTimestamp,
        DateTime.now().millisecondsSinceEpoch,
      );
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        for (var i = 0; i < 4; i++) ...[
          _buildBlinkingText(
            i == 0
                ? _timeDiff.days
                : i == 1
                ? _timeDiff.hours
                : i == 2
                ? _timeDiff.minutes
                : _timeDiff.seconds,
          ),
          if (i != 3) ...[
            SizedBox(width: widget.spacing),
            _buildColon(context),
            SizedBox(width: widget.spacing),
          ],
        ],
      ],
    );
  }

  Widget _buildBlinkingText(String text) {
    return Text(text, style: _textStyle.copyWith(color: widget.color));
  }

  Widget _buildColon(BuildContext context) {
    return FadeTransition(
      opacity: _animationController,
      child: Text(':', style: _textStyle.copyWith(color: widget.color)),
    );
  }
}
